﻿using System.Linq;
using System.Web.Mvc;
using Yonkly.Models;
using Yonkly.Utility;

namespace Yonkly.Controllers
{

    /// <summary>
    /// This is a link controller
    /// </summary>
    public class LinkController : Controller
    { 

        protected override void HandleUnknownAction(string actionName)
        {
           View(actionName);
        }

        public ActionResult View(string linkid)
        {
            //treat as a link
            using (YonklyDataContext dc = new YonklyDataContext())
            {
                var query = dc.Links.Where(link => link.Id == linkid);
                if (query.Count() > 0)
                {
                    var url = query.First().Url;
                    return Redirect(url);
                }
            }
            return RedirectToAction("Badlink"); 
        }

        [NonAction]
        public static string CreateLink(string url)
        {
            using (YonklyDataContext dc = new YonklyDataContext())
            {
                if (dc.Links.Count(link => link.Url == url.ToLower()) > 0)
                {
                    //check if link already exists
                    return dc.Links.First(link => link.Url == url.ToLower()).Id;
                }

                var linkid = GetUniqueLinkId();
                Link newlink = new Link();
                newlink.Id = linkid;
                newlink.Url = url.ToLower();
                dc.Links.InsertOnSubmit(newlink);
                dc.SubmitChanges();
                return linkid;
            }
        }

        private static string GetUniqueLinkId()
        {
            string linkid = string.Empty;
            bool isUnique;
            for (int i = 0; i < 5; i++)
            {
                linkid += Utils.GetRandomCharacter();
            }
            using (YonklyDataContext dc = new YonklyDataContext())
            {
                var results = dc.Links.Where(link => link.Id == linkid);
                isUnique = results.Count() > 0 ? false : true;
            }
            return isUnique ? linkid : GetUniqueLinkId();
        }
    }
}
